from django.shortcuts import render

import re

from django.db import DatabaseError
from django.http import HttpResponseForbidden, JsonResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

# from xiaoyu_mall.apps.users.models import User    应用目录变更后不要使用这种方式来导包
# 推荐使用如下的相对路径来导包
from .models import User

from xiaoyu_mall.utils.response_code import RETCODE
from django.contrib.auth import authenticate, login, logout


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        if not all([username, password]):
            return HttpResponseForbidden('缺少必要参数')

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return HttpResponseForbidden('请输入正确的用户名')

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return HttpResponseForbidden('请输入8-20位的密码')

        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '账号或密码错误'})

        return HttpResponseRedirect(reverse('contents:index'))

class MobileCountView(View):
    """手机号唯一性校验"""

    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        print(count)
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})

class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})

class RegisterView(View):
    # get请求，
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 第一步：接收请求参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        # 第二步：判断参数是否完整
        if not all([username, password, mobile, allow]):
            return HttpResponseForbidden('缺少必要参数')
        # 用户名长度校验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return HttpResponseForbidden('请输入5-20个字符的用户名')
        # 检验密码格式
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('请输入8-20位的密码')
        # 检验两次密码一致
        if password != password2:
            return HttpResponseForbidden('两次密码不一致')
        # 校验手机号
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden('请输入正确的手机号')
        # 提醒勾选协议
        if allow != 'on':
            return HttpResponseForbidden('请勾选协议')
        # 第三步：保存注册数据
        try:
            User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        # 返回注册结果
        return redirect(reverse('contents:index'))
